import { defineStore } from "pinia";
import { reqToken, reqUserInfo, reqLogout } from "@/api/user";
import { setToken, getToken, removeToken } from "@/utils/token-utils";
import type { ILogin, IUserInfo } from "@/api/user";
import { remove } from "nprogress";
import { staticRoutes, allAsyncRoutes, anyRoute } from "@/router/routes";
import type { RouteRecordRaw } from "vue-router";
import { cloneDeep } from "lodash";
import router from "@/router/index";
interface IState {
  token: string;
  userInfo: IUserInfo;
  menuRoutes: RouteRecordRaw[];
}
function getAsyncRoutes(
  routes: RouteRecordRaw[],
  userRoutes: string[]
): RouteRecordRaw[] {
  const menuRoutes: RouteRecordRaw[] = [];
  routes.forEach((r) => {
    if (userRoutes.includes(r.name! as string)) {
      if (Array.isArray(r.children)) {
        r.children = getAsyncRoutes(r.children, userRoutes);
      }

      menuRoutes.push(r);
    }
  });
  menuRoutes.push(anyRoute);
  return menuRoutes;
}
function resetRoute() {
  allAsyncRoutes.forEach((item) => {
    if (router.hasRoute(item.name!)) {
      router.removeRoute(item.name!);
    }
    router.removeRoute(anyRoute.name!);
  });
}
export const setUserStore = defineStore<string, IState, any, any>("user", {
  state() {
    return {
      token: getToken() || "",
      userInfo: {
        name: "",
        avatar: "",
        buttons: [],
        roles: [],
        routes: [],
      },
      menuRoutes: [],
    };
  },
  actions: {
    async login(username: string, password: string) {
      try {
        let result = (await reqToken(username, password)) as any;
        // console.log(result);
        this.token = result.token;
        setToken(this.token);
      } catch (e) {
        console.log(e);
      }
    },
    async getUserInfo() {
      try {
        let result = await reqUserInfo();

        this.userInfo = {
          ...result,
        };

        const userRoutes = getAsyncRoutes(
          cloneDeep(allAsyncRoutes),
          this.userInfo.routes
        );
        this.menuRoutes = [...staticRoutes];
        this.menuRoutes.push(...userRoutes);
        userRoutes.forEach((r) => {
          router.addRoute(r);
        });
      } catch (e) {
        this.clearUserInfo();

        console.log(e);
      }
    },
    async remove() {
      try {
        await reqLogout();
        this.clearUserInfo();
      } catch (e) {
        console.log(e);
      }
    },
    clearUserInfo() {
      (this.token = ""),
        (this.userInfo = {
          name: "",
          avatar: "",
          buttons: [],
          roles: [],
          routes: [],
        });
      removeToken();
      resetRoute();
      // router.push("/login");
    },
  },
});
